package jvm;

import java.util.concurrent.CountDownLatch;

public class CountThreadDemo {

  public static void main(String[] args) {

    Mex mex = new Mex();
    CountDownLatch countDownLatch = new CountDownLatch(100);
    for (int i = 0; i < 50000; i++) {
      Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
          int a = 0;
          synchronized (mex) { //加上synchronized 就不会有多个线程 获取同一份 cont 了
            a = mex.count;
            Thread.yield();
            //对 count 的修改对其他线程是可见的，符号管程 规则
            mex.count = a + 1;
          }
          countDownLatch.countDown();
        }
      });

      thread.start();

    }
    try {
      countDownLatch.await();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    System.out.println(mex.count);

  }

  static class Mex {
    int count;
  }

}


